"""
Verification script for the combined /api/v1/aippt/generation/ppt endpoint
Tests the new endpoint that combines createTask + generatePptx in one API call
"""
import sys
import os
from dotenv import load_dotenv
import requests
import json

# Load environment variables
load_dotenv()

# Configuration
API_BASE_URL = "http://localhost:8001"
ENDPOINT = "/api/v1/aippt/generation/ppt"


def test_combined_ppt_endpoint():
    """Test the combined PPT generation endpoint"""
    print("=" * 60)
    print("Testing Combined PPT Generation Endpoint")
    print(f"Endpoint: {ENDPOINT}")
    print("=" * 60)

    # First, get a template ID
    print("\n[Step 1] Getting a template ID...")
    print("-" * 60)

    templates_endpoint = "/api/v1/aippt/templates"
    templates_payload = {
        "current": 1,
        "size": 5,
        "type": 1
    }

    try:
        response = requests.post(
            f"{API_BASE_URL}{templates_endpoint}",
            json=templates_payload,
            params={"lang": "zh"}
        )
        response.raise_for_status()
        templates_data = response.json()

        if templates_data.get('success') and templates_data.get('data', {}).get('list'):
            template_id = templates_data['data']['list'][0]['id']
            template_name = templates_data['data']['list'][0].get('name', 'Unknown')
            print(f"SUCCESS: Got template ID: {template_id}")
            print(f"Template name: {template_name}")
        else:
            print("ERROR: Failed to get templates")
            print(json.dumps(templates_data, indent=2, ensure_ascii=False))
            return

    except Exception as e:
        print(f"ERROR getting templates: {str(e)}")
        return

    # Test the combined endpoint
    print("\n[Step 2] Testing combined PPT generation endpoint...")
    print("-" * 60)

    # Prepare test data
    test_payload = {
        "task_type": 6,  # Paste text content
        "content": "Artificial Intelligence and Machine Learning in Modern Business",
        "markdown": """# Artificial Intelligence and Machine Learning in Modern Business

## Introduction
### What is AI and ML?
- Artificial Intelligence: Simulation of human intelligence
- Machine Learning: Subset of AI that learns from data
- Deep Learning: Advanced ML using neural networks

## Business Applications
### Key Use Cases
- Customer service automation
- Predictive analytics
- Fraud detection
- Personalized recommendations

## Benefits
### Advantages for Business
- Increased efficiency
- Cost reduction
- Better decision making
- Enhanced customer experience

## Challenges
### Implementation Hurdles
- Data quality issues
- High initial investment
- Skill gap
- Ethical considerations

## Future Trends
### What's Next
- Edge AI
- Explainable AI
- AI regulation
- Democratization of AI
""",
        "template_id": template_id
    }

    print("Request payload:")
    print(json.dumps({
        **test_payload,
        "markdown": test_payload["markdown"][:100] + "..."
    }, indent=2, ensure_ascii=False))

    try:
        response = requests.post(
            f"{API_BASE_URL}{ENDPOINT}",
            json=test_payload,
            timeout=60
        )
        response.raise_for_status()
        result = response.json()

        print("\nResponse:")
        print(json.dumps(result, indent=2, ensure_ascii=False))

        if result.get('success'):
            data = result.get('data', {})
            print("\n" + "=" * 60)
            print("SUCCESS: PPT Generated!")
            print("=" * 60)
            print(f"Task ID: {data.get('task_id')}")

            ppt_info = data.get('pptInfo')
            if ppt_info:
                print(f"PPT ID: {ppt_info.get('id')}")
                print(f"Subject: {ppt_info.get('subject')}")
                print(f"Total Pages: {ppt_info.get('totalPage')}")
                print(f"Cover URL: {ppt_info.get('coverUrl')}")
                print(f"File URL: {ppt_info.get('fileUrl')}")
                print(f"Template ID: {ppt_info.get('templateId')}")
        else:
            print(f"\nERROR: Request failed with code {result.get('code')}")
            print(f"Message: {result.get('message')}")

    except requests.exceptions.RequestException as e:
        print(f"\nERROR making request: {str(e)}")
        if hasattr(e.response, 'text'):
            print(f"Response: {e.response.text}")
    except Exception as e:
        print(f"\nERROR: {str(e)}")
        import traceback
        traceback.print_exc()

    print("\n" + "=" * 60)
    print("Test completed")
    print("=" * 60)


if __name__ == "__main__":
    # Check if server is running
    try:
        response = requests.get(f"{API_BASE_URL}/docs", timeout=5)
        print(f"Server is running at {API_BASE_URL}")
    except:
        print(f"ERROR: Server is not running at {API_BASE_URL}")
        print("Please start the server first: python src/main.py")
        sys.exit(1)

    test_combined_ppt_endpoint()
